import 'package:detect/entity/entity.dart';
import 'package:detect/notifier/fpga_time.dart';
import 'package:detect/notifier/state.dart';
import 'package:detect/utils/db_util.dart';
import 'package:detect/utils/detect_util.dart';
import 'package:detect/utils/global.dart';
import 'package:detect/utils/option_util.dart';
import 'package:detect/utils/ws_util.dart';
import 'package:flutter/material.dart';
import 'package:log4f/log4f.dart';
import 'package:provider/provider.dart';

class DetectNotifier extends ChangeNotifier {
  void init(final BuildContext context) {
    WSUtil.connect().listener([
      ReceiveMsgListener("detect", (response) {
        try {
          Map<String, dynamic> lora = response['lora'];
          //{"channel":31,"code":255,"doppler":0,"freq":5062500,"local_id":123,"msg_type":0,"mulpath":0,"noise":0,"role":0,"signal":62,"src_id":169,"target_id":123}
          DetectTaskEntity? detectTask = DetectUtil.instance.detecting;
          if (detectTask == null || lora['freq'] == null) return false;
          String time = context.read<FpgaTimeNotifier>().format("yyyy-MM-dd HH:mm:ss");
          int channel = lora['channel'], hz = lora['freq'];
          double signal = double.parse(lora['signal'].toString()),
              noise = double.parse(lora['noise'].toString()),
              doppler = double.parse(lora['doppler'].toString()),
              multiPath = double.parse(lora['mulpath'].toString());
          GeneralTaskResultEntity result = GeneralTaskResultEntity(detectTask.id!, time, channel, hz, signal, noise, doppler, multiPath);
          DBApi.generalTaskResult.insert(result).then((value) => notifyListeners());
        } catch (e) {
          // debugPrint("连续探测数据处理异常 => ${e.toString()}");
          Log4f.e(msg: e.toString(), tag: "连续探测数据处理异常");
        }
        return false;
      }),
      ReceiveMsgListener("detect2", (response) {
        try {
          Map<String, dynamic> wave = response['wave'];
          //{"channel":0,"data":"9ABCDEFGHIJKLM","data_base64":"OUFCQ0RFRkdISUpLTE0=","freq":2200000,"local_id":25,"lost":0.2,"modem_type":0,"src_id":0,"sync":0.8,"target_id":0,"time":"15:14:11"}
          DetectTaskEntity? detectTask = DetectUtil.instance.detecting;
          if (detectTask == null || wave['freq'] == null) return false;
          String time = wave['time'], data = wave['data'], modemType = ModemType.values[wave['modem_type'] ?? 0].name;
          List<int> hms = time.split(":").map((e) => int.parse(e)).toList();
          time = Global.parseTime(DateTime.now().copyWith(hour: hms[0], minute: hms[1], second: hms[2]))!;
          int channel = wave['channel'], hz = wave['freq'];
          PickTaskResultPackageEntity result = PickTaskResultPackageEntity(detectTask.id!, time, data, channel, modemType, hz);
          DBApi.pickTaskResultPackage.insert(result).then((value) => notifyListeners());
        } catch (e) {
          // debugPrint("选频探测数据处理异常 => ${e.toString()}");
          Log4f.e(msg: e.toString(), tag: "选频探测数据处理异常");
        }
        return false;
      }),
      ReceiveMsgListener("detect2_report", (response) {
        try {
          Map<String, dynamic> data = response['data'];
          //{"c0_droped":1.0,"c0_snr":8.411481857299805,"c0_synced":1.0,"c1_droped":1.0,"c1_snr":12.009451866149902,"c1_synced":1.0,"c3_droped":1.0,"c3_snr":8.751680374145508,"c3_synced":1.0,"freq":2900000,"ft8_packets":1,"lora_snr":57,"received_time":"13:56:52"}
          DetectTaskEntity? detectTask = DetectUtil.instance.detecting;
          if (detectTask == null || data['freq'] == null) return false;
          String time = data['received_time'];
          List<int> hms = time.split(":").map((e) => int.parse(e)).toList();
          DateTime dateTime = DateTime.now().copyWith(hour: hms[0], minute: hms[1]+1, second: 0);
          time = Global.parseTime(dateTime, resolve: "yyyy-MM-dd HH:mm")!;
          int hz = data['freq'];
          double syncC0 = data['c0_synced'],
              lostC0 = data['c0_droped'],
              syncC1 = data['c1_synced'],
              lostC1 = data['c1_droped'],
              syncC3 = data['c3_synced'],
              lostC3 = data['c3_droped'],
              snrLora = double.parse(data['lora_snr'].toString()),
              snrC0 = double.parse(data['c0_snr'].toString()),
              snrC1 = double.parse(data['c1_snr'].toString()),
              snrC3 = double.parse(data['c3_snr'].toString());
          PickTaskResultEntity result = PickTaskResultEntity(detectTask.id!, time, hz, syncC0, lostC0, syncC1, lostC1, syncC3, lostC3, snrLora, snrC0, snrC1, snrC3);
          DBApi.pickTaskResult.insert(result).then((resultId) {
            if (resultId == null) {
              Log4f.e(msg: "选频探测数据录入失败", tag: "数据创建失败");
            } else {
              DBApi.pickTaskResultPackage.setResultId(resultId, dateTime, hz).then((value) => notifyListeners());
            }
          });
        } catch (e) {
          Log4f.e(msg: e.toString(), tag: "选频探测综合数据处理异常");
        }
        return false;
      }),
    ]);
  }
}
